/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.net.*;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
import beans.InfoSyncStorage;

/**
 *
 * @author pascal
 */
public class Sync extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response, String token)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Sync</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Sync at " + request.getContextPath() + "</h1>");
            out.println("<p><a href=\"http://www.flickr.com/services/oauth/authorize?oauth_token=" + token + "\">click</a></p>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        InfoSyncStorage store = new InfoSyncStorage();
        if (store.getTokenAcces().isEmpty()) {
            try {

                long time = System.currentTimeMillis();
                time = time / 1000;
                time = time - 10;
                Random rand = new Random();
                int nomus = rand.nextInt(99999999);
                String requete = "GET&http%3A%2F%2Fwww.flickr.com%2Fservices%2Foauth%2Frequest_token"
                        + "&oauth_callback%3Dhttp%253A%252F%252Fwww.api.test.blaboum.com%253A1337%252FTestFlickrApi%252FAcces"
                        + "%26oauth_consumer_key%3Da93aa00b458673dfdbf5308565040fb2"
                        + "%26oauth_nonce%3D" + nomus
                        + "%26oauth_signature_method%3DHMAC-SHA1"
                        + "%26oauth_timestamp%3D" + time
                        + "%26oauth_version%3D1.0";

                store.setAppSecret("da29e5c397f32c48");
                store.setAppKey("a93aa00b458673dfdbf5308565040fb2");
                SecretKeySpec keySpec = new SecretKeySpec(
                        "da29e5c397f32c48&".getBytes(),
                        "HmacSHA1");

                Mac mac = Mac.getInstance("HmacSHA1");
                mac.init(keySpec);
                byte[] result = mac.doFinal(requete.getBytes());

                BASE64Encoder encoder = new BASE64Encoder();
                String sig = encoder.encode(result);
                System.out.println(sig);


                String lien = "http://www.flickr.com/services/oauth/request_token"
                        + "?oauth_nonce=" + nomus
                        + "&oauth_timestamp=" + time
                        + "&oauth_consumer_key=a93aa00b458673dfdbf5308565040fb2"
                        + "&oauth_signature_method=HMAC-SHA1"
                        + "&oauth_version=1.0"
                        + "&oauth_signature=" + sig
                        + "&oauth_callback=http%3A%2F%2Fwww.api.test.blaboum.com%3A1337%2FTestFlickrApi%2FAcces";



                URL oracle = new URL(lien);
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(oracle.openStream()));

                String info = "";
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    info += inputLine;
                }
                in.close();

                String[] infos = info.split("&");
                String acces = infos[0].split("=")[1];
                String token = infos[1].split("=")[1];
                String tokenSecret = infos[2].split("=")[1];
                store.setTokenRequest(token);
                store.setTokenSecret(tokenSecret);
                System.out.println(acces + " " + token + " " + tokenSecret);






                processRequest(request, response, token);
            } catch (InvalidKeyException ex) {
                Logger.getLogger(Sync.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(Sync.class.getName()).log(Level.SEVERE, null, ex);
            }
        }else{
            response.sendRedirect("Acces");
        }
            
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response, "");
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
